package org.janon.httpproxy;

import java.awt.Rectangle;
import java.io.IOException;
import java.io.OutputStream;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JViewport;

public class LogList extends OutputStream
{
	private JList list = null;
	private DefaultListModel listModel = null;

	public LogList()
	{
		listModel = new DefaultListModel();
		list = new JList(listModel);
	}

	public JList getList()
	{
		return list;
	}

	public void write(int b) throws IOException
	{
	}

	public void close() throws IOException
	{
		super.close();
	}

	public void flush() throws IOException
	{
		super.flush();
	}

	public void write(byte[] b, int off, int len) throws IOException
	{
		if (list != null)
		{
			if (listModel.getSize() == 500)
			{
				listModel.remove(0);
			}
			listModel.add(listModel.getSize(), new String(b, off, len));
			scrollToVisible(list, listModel.getSize()-1,false);
		}
	}

	public void write(byte[] b) throws IOException
	{
		this.write(b, 0, b.length);
	}
	
	public static void scrollToVisible(JList list, int rowIndex, boolean center)
	{
	    if (!(list.getParent() instanceof JViewport))
	    {
	        return;
	    }

	    JViewport viewport = (JViewport)list.getParent();

	    Rectangle rect = list.getCellBounds(rowIndex, rowIndex);
	    Rectangle viewRect = viewport.getViewRect();
	    rect.setLocation(rect.x - viewRect.x, rect.y - viewRect.y);

	    if (center)
	    {
	        int centerX = (viewRect.width - rect.width) >> 1;
	        int centerY = (viewRect.height - rect.height) >> 1;

	        if (rect.x < centerX)
	        {
	            centerX = -centerX;
	        }
	        if (rect.y < centerY)
	        {
	            centerY = -centerY;
	        }
	        rect.translate(centerX, centerY);
	    }

	    viewport.scrollRectToVisible(rect);
	}

}
